import { CommandDialog } from '@amcax/base';
import { CurvedCmdDialogParams } from '@app-base/types';
import { i18n } from '@app-nextmesh/common/utils';
import { NMTopoBaseCommand } from '@app-nextmesh/types';
import { useEffect, useRef, useState } from 'react';
import CmdInteractor from './CmdInteractor';
import {
  CommandFormWrapper,
  NonDialogCommandForm,
} from '@app-base/common/components/command-form';
import { schema, uiSchema } from './type';
import { CommandFormFooter } from '@app-base/common/components/command-form/footer';

const CommandRectangle = ({ title, onClose }: CurvedCmdDialogParams) => {
  // props需要为state，以确保props和mode同时更新，分发的模式不会收到错误的props
  const [formData, setFormData] = useState<any>(null);
  const cmdRef = useRef<CmdInteractor>(null);
  useEffect(() => {
    cmdRef.current = new CmdInteractor();
    cmdRef.current.addExit(onClose);
    return () => {
      cmdRef.current?.destroy();
      cmdRef.current = null;
    };
  }, []);
  return (
    <CommandDialog
      title={title}
      onClose={onClose}
      placement='topLeft'>
      <NonDialogCommandForm
        schema={schema}
        extraUiSchema={uiSchema}
        formData={formData}
        showCancel={false}
        onChange={(data) => {
          setFormData(data.formData);
          cmdRef.current?.setPlaneMode(data.formData?.planeType);
        }}
        showSubmit={false}></NonDialogCommandForm>
      <CommandFormWrapper>
        <CommandFormFooter
          onClose={onClose}
          cancelText='关闭'
          showSubmit={false}
        />
      </CommandFormWrapper>
    </CommandDialog>
  );
};

export const cmdTopoRectangle: NMTopoBaseCommand = {
  id: 'cmdTopoRectangle',
  icon: 'commands/sketch/center-rectangle',
  label: 'command.topo.rectangle',
  create: (label: string, onClose: () => void, props) => (
    <CommandRectangle
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
      placement='topLeft'
    />
  ),
};
